var tableElem = "LAY-home-pagePart-list";
var formElem = "LAY-home-pagePart-listform";
var tableToolsElem = "LAY-home-pagePart-tools";
var formSubmitElem = "LAY-home-pagePart-listform-submit";
var formUrl = '/home/page/part/listform'
var historyUrl = '/home/page/part/list'

// 列表页
layui.use(['common'], function (common) {
    var $ = layui.$
        , admin = layui.admin
        , table = layui.table
        , router = layui.router()

    var page_id = router.search.page_id
    var historyPage = router.search.path
    if (historyPage) {
        sessionStorage.setItem('historyPage', decodeURIComponent(historyPage))
    }
    $("#goBack").attr('href', sessionStorage.getItem('historyPage'));

    //页面管理
    var tableItem = table.render({
        elem: `#${tableElem}`
        , url: window.globalConfig.url_page_list + "/" + page_id
        , parseData: function (res) {
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.part.length, //解析数据长度
                "data": res.data.part
            }
        }
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', width: 100, title: '片段id', sort: true}
            , {field: 'page_id', width: 100, title: '页面id', sort: true}
            , {field: 'title', title: '名称', minWidth: 100, edit: 'text'}
            , {
                field: 'is_show', title: '是否显示', templet: '#ID-table-pagePart-is_show-switch'
            }
            , {field: 'sort', title: '排序', sort: true, edit: 'text'}
            , {title: '操作', minWidth: 220, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 15, 20, 25, 30]
        , text: {none: "暂无数据"}
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = `${formUrl}/page_id=${page_id}`;
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    // 增删改查
    table.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;

        if (obj.event === 'del') { // 删除页面
            layer.confirm('确定删除此片段？', function (index) {
                admin.req({
                    url: window.globalConfig.url_page_part_list + "/" + data.id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        layer.close(index);
                        tableItem.reloadData(); //重载表格
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改页面
            location.hash = `${formUrl}/id=${data.id}/page_id=${page_id}`;
        }
    });


    // 表单模块
    layui.data.done = function (d) {
        var remoteData = d.data
        layui.use(['form'], function () {
            var form = layui.form;
            form.render(null, formElem); //渲染该模板下的动态表单

            let editors = {
                'editor': 'content',
            }
            common.loadEditors(remoteData,editors)


            tinymce.get('editor').on("Change", (e) => {
                let title = common.extractHeadingContent(e.target.getContent())
                if (title) {
                    $("#pagePartTitle").val(title);
                }
                // e.target.setContent((common.fillEmptyAltInRichText(e.target.getContent())));
            })


            form.on(`submit(${formSubmitElem})`, function (data) {
                var field = data.field; //获取提交的字段
                field.is_show = field.is_show === undefined ? 0 : field.is_show;
                field = common.getEditorsContent(field,editors)

                let url = window.globalConfig.url_page_part_list;
                let type = "POST";
                if (field.id) {
                    url += "/" + field.id;
                    type = "PUT"
                }

                //提交 Ajax 成功后，关闭当前弹层并重载表格
                admin.req({
                    url: url,
                    type: type,
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        location.hash = `${historyUrl}/page_id=${layui.router().search.page_id}`
                    }
                })
            });
        });
    };


    // 表格文本修改
    common.tableTextEditor(tableElem, window.globalConfig.url_page_part_list, 'id')

    // 表格的切换器修改
    common.tableSwitchEditor('pagePart-is_show-status', window.globalConfig.url_page_part_list)
})